import React, {Component} from "react";
import PropTypes from 'prop-types';

import * as API from '../../shared/http'
import UserHeader from "./UserHeader";
import Content from "./Content";
import Image from "./Image";
import Link from "./Link";
import PostActionSection from "./PostActionSection";
import Comments from "../comment/Comments";
import DisplayMap from "../map/DisplayMap";

import RouterLink from '../router/Link';
import orderBy from "lodash/orderBy";

export class Post extends Component{
  static propTypes = {
    id: PropTypes.string,
  };
  constructor(props) {
    super(props);
    this.state = {
      post: null,
      comments: [],
      showComments: true, // 查看评论，默认查看
      user: this.props.user,
    };
    this.loadPost = this.loadPost.bind(this);
    this.loadComments = this.loadComments.bind(this);
    this.createComment = this.createComment.bind(this);
  }
  componentDidMount() {
    this.loadPost(this.props.id);
    this.loadComments(this.props.id)
  }
  createComment(payload){
    API.createComment(payload)
        .then(res => {
          return res.json().then(comment => {
            this.setState(() => ({
              comments: orderBy(this.state.comments.concat([comment]),'date','asc')
            }))
          })
        })
  }

  loadPost(id){
    API.fetchPost(id)
        .then(res => {
          return res.json().then(post => {
            this.setState(() => ({post}))
          })
        })
  }
  loadComments(postId){
    API.fetchCommentsForPost(postId)
        .then(res => {
          return res.json().then(comments => {
            this.setState(() => ({
              comments: orderBy(comments,'date','asc'),
            }))
          })
        })
  }

  render() {
    return this.state.post ? (
        <div className="post">
          <RouterLink to={`/posts/${this.state.post.id}`}>
            <span>
              <UserHeader date={this.state.post.date} user={this.state.post.user} />
              <Content post={this.state.post} />
              <Image post={this.state.post} />
              <Link link={this.state.post.link} />
            </span>
          </RouterLink>
          <PostActionSection showComments={this.state.showComments} />
          <Comments
            comments={this.state.comments}
            show={this.state.showComments}
            post={this.state.post}
            user={this.props.user}
            handleSubmit={this.createComment}
          />
          {this.state.post.location !== null &&
            <DisplayMap
                key={`displayMap-${this.state.post.id}`}
                id={this.state.post.id}
                location={this.state.post.location}
                displayOnly={false}
                zoom={10} />
          }
        </div>
    ) : null;
  }
}
